###############################################################################
# This file provides code for  
#
# Moore, Ryan T. and Nirmala Ravishankar. ``Who Loses in Direct Democracy?''.  
# Social Science Research, 41(3):646-656, May 2012.
#
# Performs 2002 - 2004 Imputations
###############################################################################

library(Amelia)

lat439m <- lat439[, c("region", "gender", "race", "vote", "ideology", "party", "age", "educ", "income", "margin")]
lat449m <- lat449[, c("region", "gender", "race", "vote", "ideology", "party", "age", "educ", "income", "margin")]
lat468m <- lat468[, c("region", "gender", "race", "vote", "ideology", "party", "age", "educ", "income", "margin")]
lat478m <- lat478[, c("region", "gender", "race", "vote", "ideology", "party", "age", "educ", "income", "margin")]
lat490m <- lat490[, c("region", "gender", "race", "vote", "ideology", "party", "age", "educ", "income", "margin")]
lat500m <- lat500[, c("region", "gender", "race", "vote", "ideology", "party", "age", "educ", "income", "margin")]
lat513m <- lat513[, c("region", "gender", "race", "vote", "ideology", "party", "age", "educ", "income", "margin")]

lat.na <- rbind(  ## omit 439 and 449: duplicates from prev. analysis
cbind(lat468m, prop=lat468$prop, year = lat468$year, type = lat468$type, outcome = lat468$outcome, winner = lat468$winner),  
cbind(lat478m, prop=lat478$prop, year = lat478$year, type = lat478$type, outcome = lat478$outcome, winner = lat478$winner), 
cbind(lat490m, prop=lat490$prop, year = lat490$year, type = lat490$type, outcome = lat490$outcome, winner = lat490$winner), 
cbind(lat500m, prop=lat500$prop, year = lat500$year, type = lat500$type, outcome = lat500$outcome, winner = lat500$winner), 
cbind(lat513m, prop=lat513$prop, year = lat513$year, type = lat513$type, outcome = lat513$outcome, winner = lat513$winner))

set.seed(550)
lat.mi <- amelia(lat.na, noms = c("region", "gender", "race", "vote"), ords = c("ideology", "party", "age", "educ", "income"), idvars = c("prop", "year", "type", "winner", "outcome"))
for(i in 1:length(lat.mi$imputations)){
	tmp <- lat.mi$imputations[[i]]
	tmp[is.na(tmp$winner), "winner"] <- as.numeric(tmp$vote[is.na(tmp$winner)] == tmp$outcome[is.na(tmp$winner)])
	lat.mi$imputations[[i]] <- tmp
}

rm(lat439m, lat449m, lat468m, lat478m, lat490m, lat500m, lat513m)
rm(lat439, lat449, lat468, lat478, lat490, lat500, lat513)
rm(i, tmp)
